#include "../inc/Ui/WebForm.h"
#include "../inc/Ui/FindLocationForm.h"
#include "../inc/Utility/MyParserTiengViet.h"
#include "../inc/Utility/VietnameseReader.h"
#include <FApp.h>
#include "../inc/Ui/TwitterLoginForm.h"
#include"../inc/Model/CurrentLocationService.h"
#include "Ui/ShowFindLocationResultForm.h"
#include "../inc/Ui/BookmarkPlaceViewerForm.h"
#include "../inc/Ui/BookmarkPlaceForm.h"
#include "../inc/Ui/GoogleBuzz/GoogleBuzzMenuForm.h"
#include "../inc/Ui/FindMultipointDirectionForm.h"

using namespace Osp::Io;
using namespace Osp::App;
using namespace Osp::Social;
using namespace Osp::Social::Services;

int WebForm::FormId = -1;

WebForm::WebForm(void) :
	pWeb(null) {
	isFirstStart = true;
	m_Lat = L"";
	m_Lng = L"";
	pBitmapLaBan = null;
	degree = 0;
	pTimer = new Timer();
	showCompass = false;
	latitude = 0;
	longitude = 0;
}

WebForm::~WebForm(void) {

}

bool WebForm::Initialize() {
	return true;
}

result WebForm::OnInitializing(void) {
	result r = E_SUCCESS;

	// TODO: Add your initialization code here
	ArrayQueryJavascriptAddMarker = new ArrayList();
	ArrayQueryJavascriptAddMarker->Construct();

	this->SetSoftkeyEnabled(SOFTKEY_0, true);
	this->SetSoftkeyEnabled(SOFTKEY_1, true);
	Application *pApp = Application::GetInstance();

	String temp = L"";

	pApp->GetAppResource()->GetString("IDS_WEBFORM_SOFTKEY_0", temp);
	this->SetSoftkeyText(SOFTKEY_0, temp);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_SOFTKEY_1", temp);
	this->SetSoftkeyText(SOFTKEY_1, temp);

	this->SetSoftkeyActionId(SOFTKEY_0, ID_SOFTKEY_ZOOMIN);
	this->SetSoftkeyActionId(SOFTKEY_1, ID_SOFTKEY_ZOOMOUT);

	this->AddSoftkeyActionListener(SOFTKEY_0, *this);
	this->AddSoftkeyActionListener(SOFTKEY_1, *this);

	//Option menu
			pOptionMenu = new OptionMenu();
			pOptionMenu->Construct();

			pApp->GetAppResource()->GetString(L"IDS_WEBFORM_OPTIONMENU_MAPTYPE",temp);

	pOptionMenu->AddItem(temp, ID_OPTIONMENU_MAPTYPE);

	pApp->GetAppResource()->GetString(L"IDS_WEBFORM_OPTIONMENU_FINDLOCATION", temp);
	pOptionMenu->AddItem(temp, ID_OPTIONMENU_FINDLOCATION);

	pApp->GetAppResource()->GetString(L"IDS_WEBFORM_OPTIONMENU_FINDDIRECTION", temp);
	pOptionMenu->AddItem(temp, ID_OPTIONMENU_FINDDIRECTION);

	pApp->GetAppResource()->GetString(L"IDS_FINDDIRECTION_TWOPOINT", temp);
	pOptionMenu->AddSubItem(2, temp, ID_FINDDIRECTION_TWOPOINT);

	pApp->GetAppResource()->GetString(L"IDS_FINDDIRECTION_MULTIPOINT", temp);
	pOptionMenu->AddSubItem(2, temp, ID_FINDDIRECTION_MULTIPOINT);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_WEATHER", temp);
	pOptionMenu->AddItem(temp,ID_OPTIONMENU_WEATHER);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_FAVOUR",temp);
	pOptionMenu->AddItem(temp,ID_OPTIONMENU_VITRIYEUTHICH);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_SEARCHPLACE", temp);
	pOptionMenu->AddItem(temp, ID_OPTIONMENU_TIMVITRI);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_TRAFFICJAM", temp);
	pOptionMenu->AddItem(temp, ID_OPTIONMENU_KETXE);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_COMPASS", temp);
	pOptionMenu->AddItem(temp, ID_OPTIONMENU_COMPASS);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_COMPASS.SHOW", temp);
	pOptionMenu->AddSubItem(7, temp, ID_OPTIONMENU_SHOWCOMPASS);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_COMPASS.HIDE", temp);
	pOptionMenu->AddSubItem(7, temp, ID_OPTIONMENU_HIDECOMPASS);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_SOCIETY", temp);
	pOptionMenu->AddItem(temp, ID_OPTIONMENU_SOCIETY);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_SOCIETY.TWITTER", temp);
	pOptionMenu->AddSubItem(8, temp, ID_OPTIONMENU_TWITTERFORM);

	pApp->GetAppResource()->GetString("IDS_WEBFORM_OPTIONMENU_SOCIETY.GOOGLEBUZZ", temp);
	pOptionMenu->AddSubItem(8, temp, ID_OPTIONMENU_GOOGLEBUZZ);


	pOptionMenu->AddItem("AugmentReality",ID_OPTIONMENU_AUGMENTREALITY);

	this->AddOptionkeyActionListener(*this);
	pOptionMenu->AddActionEventListener(*this);
	this->SetOptionkeyActionId(ID_OPTIONMENU);

	image.Construct();
	pBitmapLaBan = image.DecodeN(L"/Res/Compass.png", BITMAP_PIXEL_FORMAT_ARGB8888);

	//register for current location


	r = CreateWebControl();
	if (IsFailed(r))
	{
	//	AppLog("CreateMainForm() has failed.\n");
		goto CATCH;
	}
	WebController::SetWebControl(pWeb);
	//pFrame
//	pFrame = static_cast<Frame*>(this->GetParent());


	pWeb->AddTouchEventListener(*this);


	pWeb->LoadUrl("file:///Res/index.html");

	pTimer->Construct(*this);

	r = sensorManager.Construct();
	if (IsFailed(r)) {
		return false;
	}
	CreateCurrentLocationButton();
	CurrentLocationService::getInstance()->AddMember(*this);

	return r;

	CATCH:
	return false;
}

result WebForm::OnTerminating(void) {
	result r = E_SUCCESS;

	// TODO: Add your termination code here
	AppLog("Bat dau xoa webform");
	if (pBitmapLaBan != null) {
		delete pBitmapLaBan;
	}

	if (pTimer != null) {
		delete pTimer;
	}

	if (pOptionMenu != null) {
		delete pOptionMenu;
	}
	return r;
}

result WebForm::CreateCurrentLocationButton() {

	Rectangle rect;
	rect.x = 10;
	rect.y = 10;
	rect.width = 112;
	rect.height = 80;

	Button *pButtonCurrentLocation = null;
	pButtonCurrentLocation = new Button();
	result r = pButtonCurrentLocation->Construct(rect, String(L""));
	if (IsFailed(r)) {
		AppLog("Can not create current location button");
		return r;
	}
	Image image;
	r = image.Construct();
	if (IsFailed(r)) {
		AppLog("Can not construct image current location button");
		return r;
	}
	Bitmap *pBitmap = image.DecodeN(String(L"/Res/ButtonLocation.png"), BITMAP_PIXEL_FORMAT_ARGB8888);
	pButtonCurrentLocation->SetNormalBackgroundBitmap(*pBitmap);
	delete pBitmap;
	pBitmap = image.DecodeN(String(L"/Res/ButtonLocation2.png"), BITMAP_PIXEL_FORMAT_ARGB8888);
	pButtonCurrentLocation->SetPressedBackgroundBitmap(*pBitmap);
	delete pBitmap;
	pButtonCurrentLocation->SetActionId(ID_BUTTON_CURRENT_LOCATION);
	pButtonCurrentLocation->AddActionEventListener(*this);
	r = this->AddControl(*pButtonCurrentLocation);
	if (IsFailed(r)) {
		AppLog("Can not add current location button to webform");
	}
	return r;
}

result WebForm::createCompassControl() {
	result r = E_SUCCESS;
	int screen_width = 0;
	int screen_height = 0;

	r = SystemInfo::GetValue("ScreenWidth", screen_width);
	TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed");

	r = SystemInfo::GetValue("ScreenHeight", screen_height);
	TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed");

	pCompass = new Label();
	r = pCompass->Construct(Rectangle((screen_width / 2 - 192), (screen_height
			/ 2 - 192), 384, 384), "");
	TryCatch(r == E_SUCCESS, ,"Label Compass is not constructed\n ");

	return r;

	CATCH: AppLog("Error = %s\n", GetErrorMessage(r));
	return r;
}
void WebForm::HienThiExpandList(FormManager*pFormManager) {
	Form *pBookmarkPlaceViewerForm = null;
	result r = pFormManager->GetForm(BookmarkPlaceViewerForm::GetFormId(),
			pBookmarkPlaceViewerForm);
	if (IsFailed(r)) {
		return;
	}

	static_cast<BookmarkPlaceViewerForm*> (pBookmarkPlaceViewerForm)->loadViTriYeuThichLenExpandable();
}
void WebForm::YeuCauKiemTraDangNhapTwitter(FormManager*pFormManager) {

	Form *pTwitterLogin = null;
	result r = pFormManager->GetForm(Form1::GetFormId(), pTwitterLogin);
	if (IsFailed(r)) {
		return;
	}

	static_cast<Form1*> (pTwitterLogin)->ExcuteLogin();
	this->RemoveControl(*pWeb);
}
void WebForm::OnActionPerformed(const Osp::Ui::Control& source, int actionId) {
	MyParserTiengViet *p = new MyParserTiengViet();
	/*KHai bao nang luong cho dien thoai*/
	BatteryLevel batterylevel = BATTERY_HIGH;
	Battery::GetCurrentLevel(batterylevel);

	String *ptrStr = null;
	String strComm = L"";

	MessageBox message;

	FormManager *pFormManager = null;
	result r = FormManager::GetInstance(pFormManager);
	Form *pForm = null;

	if (IsFailed(r)) {
		return;
	}
	switch(actionId)
	{
		case ID_SOFTKEY_ZOOMIN:
		//	AppLog("Softkey Zoom in");

			strComm = L"zoomIn();";
			ptrStr = pWeb->EvaluateJavascriptN(strComm);
			delete ptrStr;
			break;
			case ID_SOFTKEY_ZOOMOUT:
			//	AppLog("Softkey Zoom out");
			strComm = L"zoomOut();";
			ptrStr = pWeb->EvaluateJavascriptN(strComm);
			delete ptrStr;
			break;

			case ID_OPTIONMENU:
			//	AppLog("Option menu show");
			pOptionMenu->SetShowState(true);
			pOptionMenu->Show();
			break;

			case ID_OPTIONMENU_MAPTYPE:
			{
				pFormManager->SetCurrentForm(ChangeMapTypeForm::GetFormId());

			}
			break;

			case ID_OPTIONMENU_FINDLOCATION:
			{
				//		AppLog("Option menu tim kiem");

				pFormManager->SetCurrentForm(FindLocationForm::GetFormId());
				pFormManager->GetForm(FindLocationForm::GetFormId(),pForm);
				static_cast<FindLocationForm*> (pForm)->ThemDiaChiTuFileVaoDanhSach();
			}
			break;

			case ID_FINDDIRECTION_TWOPOINT:
			//AppLog("Option menu tim duong di");

			pFormManager->SetCurrentForm(FindDirectionForm::GetFormId());

			break;

			case ID_FINDDIRECTION_MULTIPOINT:
				pFormManager->SetCurrentForm(FindMultipointDirectionForm::GetFormId());
				pFormManager->GetForm(FindMultipointDirectionForm::GetFormId(), pForm);
				(static_cast<FindMultipointDirectionForm*>(pForm))->Reset();

				break;

			case ID_OPTIONMENU_KETXE:
			//AppLog("TrafficJamForm");
			pFormManager->SetCurrentForm(TrafficJamForm::GetFormId());

			break;
			case ID_OPTIONMENU_WEATHER:
			pFormManager->SetCurrentForm(WeatherForm::GetFormId());

			break;

			case ID_OPTIONMENU_VITRIYEUTHICH:
			pFormManager->SetCurrentForm(BookmarkPlaceViewerForm::GetFormId());
			HienThiExpandList(pFormManager);
			break;

			case ID_OPTIONMENU_TIMVITRI:
				pFormManager->SetCurrentForm(SearchPlaceForm::GetFormId());
				break;
			case ID_OPTIONMENU_TWITTERFORM:
				pFormManager->SetCurrentForm(Form1::GetFormId());
				YeuCauKiemTraDangNhapTwitter(pFormManager);

				break;

			case ID_BUTTON_CURRENT_LOCATION:
				SetCurrentLocation();
				break;

		 case ID_OPTIONMENU_SHOWCOMPASS:
			 RegisterCompass();
		 break;

		 case ID_OPTIONMENU_HIDECOMPASS:
			 UnRegisterCompass();
			 break;

		case ID_OPTIONMENU_AUGMENTREALITY:
		{
			float lat=CurrentLocationService::getInstance()->getLatitude();
			float lng=CurrentLocationService::getInstance()->getLongitude();
			if (lat == Float::GetMaxValue()) {
				MessageBox msg;
				msg.Construct("Chào bạn ", "Bạn chưa sử dụng chức năng GPS",
						MSGBOX_STYLE_OK, 3000);
				int i = 0;
				msg.ShowAndWait(i);
				break;
			}
			else
			{
				//KhoiTaoCamera(pFrame);
				__pStartForm->YeuCauCapNhatThongTinDiaDiemVaThoiTiet(lat, lng);
			}
		}
		break;

		case ID_OPTIONMENU_GOOGLEBUZZ:
			pFormManager->SetCurrentForm(GoogleBuzzMenuForm::GetFormId());
			pFormManager->GetForm(GoogleBuzzMenuForm::GetFormId(), pForm);
			(static_cast<GoogleBuzzMenuForm*>(pForm))->Begin();
			break;

		default:
		break;
	}
}

result WebForm::CreateWebControl(void) {
	result r = E_SUCCESS;
	int screen_width = 0;
	int screen_height = 0;

	/*screen*/
	r = SystemInfo::GetValue("ScreenWidth", screen_width);
	TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed");

	r = SystemInfo::GetValue("ScreenHeight", screen_height);
	TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed");

	/*Web*/
	pWeb = new Web();
	r = pWeb->Construct(Rectangle(0, 0, screen_width, screen_height - 38));
	TryCatch(r == E_SUCCESS, ,"Web is not constructed\n ");

	r = this->AddControl(*pWeb);

	TryCatch(r == E_SUCCESS, ,"Web is not attached\n ");
	pWeb->SetLoadingListener(this);
	pWeb->SetFocus();
	pWeb->AddTouchEventListener(*this);
	pWeb->LoadUrl("file:///Res/index.html");
	//	AppLog("CreateWebControl");
	return r;

	CATCH: AppLog("Error = %s\n", GetErrorMessage(r));
	return r;
}

//Map control function
void WebForm::SetMapTypeId(int intMapTypeId) {
	WebController::SetMapTypeIdN(pWeb, intMapTypeId);
}

void WebForm::TimKiemBanDo(IList* args) {
	String *address = (String*) args->GetAt(0);
	MyParserXml *pMyParserXml = new MyParserXml();
	String add;
	add.Append(*address);

	pMyParserXml->AddNewNode("/Home/MyFileXml.xml", "ADDRESS", add);
	String addressWeb = L"http://maps.google.com/maps/geo?q=";
	addressWeb.Append(*address);
	addressWeb.Append(L"&output=xml");

	String utf8Address = L"";
	result r = MyUtil::StringToUTF8String(addressWeb, utf8Address);
	if (IsFailed(r)) {
		utf8Address = addressWeb;
	}

	currentDownloadTask = REQUEST_FINDLOCATION;
	Downloader::downloadAndSave(utf8Address, L"/Home/FindLocation.xml", this);
	args->RemoveAll(true);
}

void WebForm::FindDirection(IList *listArg) {
	if (listArg != null) {
		if (listArg->GetCount() == 4) {

			String *strFrom = static_cast<String*> (listArg->GetAt(0));
			String *strTo = static_cast<String*> (listArg->GetAt(1));
			String *strMethod = static_cast<String*> (listArg->GetAt(2));
			Boolean *isReadResult = static_cast<Boolean*> (listArg->GetAt(3));

			m_startPoint = *strFrom;
			m_endPoint = *strTo;
			m_transport = *strMethod;
			m_readResult = isReadResult->ToBool();
			String countryCode = MyUtil::GetSystemLanguage();
			bool isVietnamese = true;
			isVietnamese = countryCode.Equals(L"vn", false);
			String language = L"vi";
			if (!isVietnamese) {
				language = L"en";
			}

			String url = L"http://toannhanb7.somee.com/Default.aspx?command=direction&from=";
			//String url = L"http://localhost:1362/Default.aspx?command=direction&from=";
			url.Append(m_startPoint);
			url.Append(L"&to=");
			url.Append(m_endPoint);
			url.Append(L"&by=");
			url.Append(m_transport);
			url.Append(L"&lg=");
			url.Append(language);
			String utf8Url = L"";
			result r = MyUtil::StringToUTF8String(url, utf8Url);
			if (IsFailed(r)) {
				utf8Url = url;
			}

			currentDownloadTask = REQUEST_FINDIRECTION;
			Downloader::downloadAndSave(utf8Url, String(L""), this);
			//WebController::VeDuongDiN(pWeb, *strFrom, *strTo, *strMethod);
		}
		else {
			String *pUrl = (String*)listArg->GetAt(0);
			String strUrl = L"http://toannhanb7.somee.com/Default.aspx?command=convertkml&url=";
			//String strUrl = L"http://localhost:1362/Default.aspx?command=convertkml&url=";
			strUrl.Append(*pUrl);
			String utf8Url = L"";
			result r = MyUtil::StringToUTF8String(strUrl, utf8Url);
			if (IsFailed(r)) {
				utf8Url = strUrl;
			}
			/*//"http://toannhanb7.somee.com/Default.aspx?command=direction&from="
			 "http://localhost:1362/Default.aspx?command=direction&from="
			 + from + "&to=" + to + "&by=" + by + "&lg=" + language;*/

			currentDownloadTask = REQUEST_FINDIRECTION;
			Downloader::downloadAndSave(utf8Url, String(L""), this);
		}
		listArg->RemoveAll(true);

		delete listArg;

	}
}
/*
 void WebForm::LayViTriHienTai() {
 pLocProvider->RequestLocationUpdates(*this, 1, false);
 }

 void WebForm::OnLocationUpdated(Osp::Locations::Location &location) {
 const QualifiedCoordinates* pQCoord = location.GetQualifiedCoordinates();
 //AppLog("OnLocationUpdated");
 if (pQCoord != null) {
 AppLog("vao trong");
 float newLatitude = pQCoord->GetLatitude();
 float newLongitude = pQCoord->GetLongitude();

 if (newLatitude != latitude || newLongitude != longitude) {
 latitude = newLatitude;
 longitude = newLongitude;
 String strComm = L"setMyLocation(\"";
 strComm.Append(latitude);
 strComm.Append("\", \"");
 strComm.Append(longitude);
 strComm.Append("\");");
 String *strR = pWeb->EvaluateJavascriptN(strComm);
 delete strR;
 pGoogle->setLatLon(latitude, longitude);
 }
 }

 }
 */
void WebForm::LocationUpdate(float longitude, float latitude) {

	this->latitude = latitude;
	this->longitude = longitude;
	WebController::SetMyLocationN(pWeb, latitude, longitude, false);
}
void WebForm::OnTouchDoublePressed(const Control &source,
		const Point &currentPosition, const TouchEventInfo &touchInfo) {
}

void WebForm::OnTouchFocusIn(const Control &source,
		const Point &currentPosition, const TouchEventInfo &touchInfo) {
}

void WebForm::OnTouchFocusOut(const Control &source,
		const Point &currentPosition, const TouchEventInfo &touchInfo) {
}

void WebForm::OnTouchLongPressed(const Control &source,
		const Point &currentPosition, const TouchEventInfo &touchInfo) {
}

void WebForm::OnTouchMoved(const Control &source, const Point &currentPosition,
		const TouchEventInfo &touchInfo) {
}

void WebForm::OnTouchPressed(const Control &source,
		const Point &currentPosition, const TouchEventInfo &touchInfo) {
}

void WebForm::OnTouchReleased(const Control &source,
		const Point &currentPosition, const TouchEventInfo &touchInfo) {
	AppLog("OnTouchReleased is called. [%d]%d,%d", touchInfo.GetPointId(), currentPosition.x, currentPosition.y);
	String *lat, *lng;
	lat = pWeb->EvaluateJavascriptN(L"getMyLat()");
	lng=pWeb->EvaluateJavascriptN(L"getMyLng()");
	if(lat->GetLength()>0&&lng->GetLength()>0)
	{
		if(lat->Equals((String )L"0")==false&&lng->Equals((String)L"0")==false)
				{
					AppLog("%S",lat->GetPointer());
					m_Lat=lat->GetPointer();
					m_Lng=lng->GetPointer();
					FormManager *pFormManager = null;
								FormManager::GetInstance(pFormManager);
								pFormManager->SetCurrentForm(BookmarkPlaceForm ::GetFormId());
				}
				else
				{
					AppLog("%S",lat->GetPointer());
					AppLog("%S",lng->GetPointer());
					AppLog("co chieu dai bang 1");
				}
			}
			else
			{
				//Khong co click len man hinh
				AppLog("KHONG CO CLICK LEN MAN HINH");
			}
}

String WebForm::getMyLat() {
	String ketqua = m_Lat;
	m_Lat = "";
	return ketqua;

}
String WebForm::getMyLng() {
	String ketqua = m_Lng;
	m_Lng = "";
	return ketqua;
}
void WebForm::DatCacMarkerViTriYeuThichLenMap() {
	MyParserXml *myPa = new MyParserXml();
	pWeb->EvaluateJavascriptN("deleteOverlays()");
	LinkedListT<MyViTriYeuThich*>*list = new LinkedListT<MyViTriYeuThich*> ();
	list = myPa->getLayMangViTriYeuThich("/Home/ViTriYeuThich.xml");
	for (int i = 0; i < list->GetCount(); i++) {
		MyViTriYeuThich*p = new MyViTriYeuThich();
		list->GetAt(i, p);
		String str = "addMarkerWithInfomation(" + p->__pLat + "," + p->__pLng
				+ ",'iconFavourite.png','" + p->__pTieuDe + "','"
				+ p->__pChuThich + "');";
		AppLog("%S", str.GetPointer());
		String *strR = pWeb->EvaluateJavascriptN(str);
		delete strR;
	}
	list->RemoveAll();
	delete list;
}

void WebForm::DatCacMakerTimKiemViTriLenMap(ArrayList *list) {
	int lenghtList = list->GetCount();
	int i = 0;
	pWeb->EvaluateJavascriptN("deleteOverlays()");
	String *strR = null;
	while (i < lenghtList) {
		String *lat, *lng;
		lat = static_cast<String*> (list->GetAt(i));
		i = i + 1;
		lng = static_cast<String*> (list->GetAt(i));
		String latString = lat->GetPointer();
		String lngString = lng->GetPointer();
		String str = "them(" + latString + "," + lngString + ");";
		strR = pWeb->EvaluateJavascriptN(str);
		delete strR;
		i = i + 1;
	}
	list->RemoveAll();
	delete list;
}

void WebForm::XoayBitmap() {

	Canvas canvas;
	Rectangle rect(0, 0, 512, 512);
	canvas.Construct(rect);
	canvas.DrawBitmap(Point(256, 256), *pBitmapLaBan, Point(256, 256), degree);

}

void WebForm::OnDataReceived(Osp::Uix::SensorType sensorType,
		Osp::Uix::SensorData& sensorData, result r) {
	float x = 0;
	if (sensorType == SENSOR_TYPE_TILT) {
		sensorData.GetValue((SensorDataKey) TILT_DATA_KEY_AZIMUTH, x);
		if (x != degree) {
			degree = x;
		}
	}
}

void WebForm::themToaDo(double lat, double lng) {
	String strComm = "addPointForDrawDirection(";
	strComm.Append(lat);
	strComm.Append(',');
	strComm.Append(lng);
	strComm.Append(");");
	String *strR = pWeb->EvaluateJavascriptN(strComm);
	delete strR;
}

void WebForm::layThongTin(String diaDiem) {

}
void WebForm::hienThiViTriKetXe(char* strPath) {
	AppLog("Hien thi vi tri ket xe");
	MyParserXml *myPa = new MyParserXml();
	LinkedListT<DiaDiemKetXe*>*list = new LinkedListT<DiaDiemKetXe*> ();
	list = myPa->getLayMangDiaDiemKetXe(strPath);

	if (list->GetCount() <= 0) {
		ThongBaoLoi("That bai");
		return;
	} else {
		String clear = "deleteOverlays()";
		pWeb->EvaluateJavascriptN("deleteOverlays()");
		AppLog("List >0");
		for (int i = 0; i < list->GetCount(); i++) {
			DiaDiemKetXe*p = new DiaDiemKetXe();
			list->GetAt(i, p);
			String latString = p->__pLat.GetPointer();
			String lngString = p->__pLng.GetPointer();
			String image;
			if (p->__pLoaiThongTin.Equals((String) L"ketxe") == true) {
				image= "ketxe.png";
			} else {
				image="raochan.png";
			}
			String str = "danhDauViTriTraffic(" + latString + "," + lngString
			+ ",'" + image + "');";
			pWeb->EvaluateJavascriptN(str);
		}
	}

}

void WebForm::OnTimerExpired(Timer &timer) {
	if (!showCompass) {
		return;
	}
	Canvas canvas;
	Rectangle rect(0, 0, 512, 512);
	canvas.Construct(rect);
	canvas.DrawBitmap(Point(256, 256), *pBitmapLaBan, Point(256, 256), degree);
	Canvas *pCanvas = pCompass->GetCanvasN();
	pCanvas->Copy(Rectangle(0, 0, 384, 384), canvas, rect);
	this->Show();
	delete pCanvas;
	timer.Start(25);
}

void WebForm::RegisterCompass() {
	if (!showCompass) {
		result r = E_SUCCESS;

		long interval = 0;

		r = sensorManager.GetMinInterval(SENSOR_TYPE_TILT, interval);
		if (IsFailed(r)) {
			return;
		}
		if (interval < 50) {
			interval = 50;
		}
		r = sensorManager.AddSensorListener(*this, SENSOR_TYPE_TILT, interval,
				false);
		if (IsFailed(r)) {
			return;
		}

		createCompassControl();

		this->AddControl(*pCompass);
		pTimer->Start(25); // FPS: 40
		showCompass = true;
	}
}

void WebForm::UnRegisterCompass() {
	if (showCompass) {
		pTimer->Cancel();
		sensorManager.RemoveSensorListener(*this);
		this->RemoveControl(*pCompass);
		showCompass = false;
	}
}

void WebForm::showResultSearchPlaceInMap(String namePlace) {
	if (latitude == 0 && longitude == 0) {
		MessageBox msg;
		msg.Construct("Chào bạn ", "Xảy ra lỗi mạng ", MSGBOX_STYLE_OK, 3000);
		int i = 0;
		msg.ShowAndWait(i);
	} else {
		pWeb->EvaluateJavascriptN("deleteOverlays()");
		String tenAnh;
		tenAnh.Append("IconMarkerPlace/");
		tenAnh.Append(namePlace);
		tenAnh.Append(".png");
		String query;
		query.Append("onLoad('");
		query.Append(latitude);
		query.Append(",");
		query.Append(longitude);
		query.Append("','");
		query.Append(namePlace);
		query.Append("','");
		query.Append(tenAnh);
		query.Append("');");

		pWeb->EvaluateJavascriptN(query);
	}

}
void WebForm::showResultSearchPlaceByPlceInMap(String address,
		String tieuChiSearch) {

	if (address.GetLength() == 0 || address.GetLength() > 140) {
		MessageBox msg;
		msg.Construct("Chào bạn ", "Địa chỉ search không hợp lệ",
				MSGBOX_STYLE_OK, 3000);
		int i = 0;
		msg.ShowAndWait(i);
	} else {
		pWeb->EvaluateJavascriptN("deleteOverlays()");
		String tenAnh;
		tenAnh.Append("IconMarkerPlace/");
		tenAnh.Append(tieuChiSearch);
		tenAnh.Append(".png");
		String query;
		query.Append("onLoad('");
		query.Append(address);
		query.Append("','");
		query.Append(tieuChiSearch);
		query.Append("','");
		query.Append(tenAnh);
		query.Append("');");

		pWeb->EvaluateJavascriptN(query);
	}
}

void WebForm::ShowLocationFriendInMap(String location, String statusText,
		String timeUpdateStatusText, String urlPhoto) {

	MyParserTiengViet *pParserTV = new MyParserTiengViet();
	statusText = pParserTV->TranformSignToUnsignInTiengViet(statusText);
	//pWeb->EvaluateJavascriptN("deleteOverlays()");
	String myQuery;
	myQuery.Append("convertAddressToCoordinate('");
	myQuery.Append(location);
	myQuery.Append("','");
	myQuery.Append(statusText);
	myQuery.Append("','");
	myQuery.Append(timeUpdateStatusText);
	myQuery.Append("','");
	myQuery.Append(urlPhoto);
	myQuery.Append("');");
	ArrayQueryJavascriptAddMarker = new ArrayList();
	ArrayQueryJavascriptAddMarker->Construct();
	ArrayQueryJavascriptAddMarker->Add(*(new String(myQuery)));
	CreateWebControl();
}
void WebForm::ShowLocationListFriendInMap(IList*listFriend) {
	//AppLog("Vao show location list friend");
	String userName;
	String location;
	String statusText;
	String updateTimeStatusText;
	MyParserTiengViet *pParserTiengViet = new MyParserTiengViet();

	ArrayQueryJavascriptAddMarker = new ArrayList();
	ArrayQueryJavascriptAddMarker->Construct();
	for (int i = 0; i < listFriend->GetCount(); i++) {

		SnsProfile *pSnsProfile =
				static_cast<SnsProfile*> (listFriend->GetAt(i));
		SnsStatusText pSnsStatus = pSnsProfile->GetStatusText();

		pSnsProfile->GetValue(SNS_PROFILE_PID_USER_NAME, userName);
		pSnsProfile->GetValue(SNS_PROFILE_PID_LOCATION, location);
		String urlPhoto;
		pSnsProfile->GetValue(SNS_PROFILE_PID_PHOTO_URL, urlPhoto);
		if (location.GetLength() > 0) {
			statusText = pParserTiengViet->TranformSignToUnsignInTiengViet(
					pSnsStatus.GetStatusText());

			userName.Append(",");
			userName.Append(pSnsStatus.GetUpdateTime().ToString());

			String myQuery;
			myQuery.Append("convertAddressToCoordinate('");
			myQuery.Append(location);
			myQuery.Append("','");
			myQuery.Append(statusText);
			myQuery.Append("','");
			myQuery.Append(userName);
			myQuery.Append("','");
			myQuery.Append("twitter.png");
			myQuery.Append("','");
			myQuery.Append(urlPhoto);
			myQuery.Append("');");
			AppLog("MyQuery:%S", myQuery.GetPointer());
			ArrayQueryJavascriptAddMarker->Add(*(new String(myQuery)));
		}
	}
	CreateWebControl();
}

/*All method to load map and listener in this*/

bool WebForm::OnHttpAuthenticationRequestedN(const Osp::Base::String& host,
		const Osp::Base::String& realm,
		const Osp::Web::Controls::AuthenticationChallenge& authentication) {
	//AppLog("WebView:OnHttpAuthenticationRequestedN");
	return true;
}

void WebForm::OnHttpAuthenticationCanceled() {
	//AppLog("WebView:OnHttpAuthenticationCanceled");
}

void WebForm::OnLoadingStarted(void) {
	//AppLog("WebView:OnLoadingStarted");
}

void WebForm::OnLoadingCanceled() {
	//AppLog("WebView:OnLoadingCanceled");
}

void WebForm::OnLoadingErrorOccurred(LoadingErrorType error,
		const String& reason) {
	Osp::Ui::Controls::MessageBox msgBox;
	Osp::Base::String errReason;
	int modalresult = 0;

	//AppLog("WebView:OnLoadingErrorOccurred");
	switch (error) {
	case WEB_ERROR_UNKNOWN:
		errReason = Osp::Base::String(L"An Unknown error");
		break;
		case WEB_REQUEST_TIMEOUT:
		errReason = Osp::Base::String(L"Request timeout");
		break;
		case WEB_NO_CONNECTION:
		errReason = Osp::Base::String(L"Network is not in service");
		break;
		case WEB_MIME_NOT_SUPPORTED:
		errReason = Osp::Base::String(L"The content type is not supported");
		break;
		case WEB_BAD_URL:
		errReason = Osp::Base::String(L"The url is invalid");
		break;
		case WEB_HTTP_RESPONSE:
		errReason = Osp::Base::String(L"HTTP response");
		break;
		default:
		errReason = Osp::Base::String(L"Not Web Error");
		break;
	}

	msgBox.Construct(L"LOADING ERROR TYPE", errReason, MSGBOX_STYLE_NONE, 3000);
	// Call ShowAndWait - draw, show itself and process events
	msgBox.ShowAndWait(modalresult);
}

void WebForm::OnLoadingCompleted() {
	if (ArrayQueryJavascriptAddMarker->GetCount() > 0) {
		//AppLog("Co danh sanh can dat marker");
		AppLog("Vao loading completed");
		ShowMarkerInArrayList();

	}
}

void WebForm::OnEstimatedProgress(int progress) {
	//AppLog("WebView:OnEstimatedProgress");

}

void WebForm::OnPageTitleReceived(const Osp::Base::String& title) {
	//AppLog("WebView:OnPageTitleReceived");
}

bool WebForm::OnLoadingRequested(const String& url, WebNavigationType type) {
	//AppLog("WebView:OnLoadingRequested");
	//UpdateEditField(url);
	return false;
}

DecisionPolicy WebForm::OnWebDataReceived(const Osp::Base::String& mime,
		const Osp::Net::Http::HttpHeader& header) {
	//AppLog("WebView:OnWebDataReceived");
	return WEB_DECISION_CONTINUE;
}
void WebForm::ShowMarkerInArrayList() {
	if (ArrayQueryJavascriptAddMarker != null
			&& ArrayQueryJavascriptAddMarker->GetCount() > 0) {
		pWeb->EvaluateJavascriptN("deleteOverlays()");
		for (int i = 0; i < ArrayQueryJavascriptAddMarker->GetCount(); i++) {
			String *query =
					static_cast<String*> (ArrayQueryJavascriptAddMarker->GetAt(
							i));
			String myQuery = query->GetPointer();
			pWeb->EvaluateJavascriptN(myQuery);
		}
		ArrayQueryJavascriptAddMarker->RemoveAll(true);
	}
}

void WebForm::OnDownloadComplete(Osp::Base::String url, Osp::Base::String path) {
	if (currentDownloadTask == REQUEST_FINDLOCATION) {

		MyParserXml *myPa = new MyParserXml();

		LinkedListT<DiaChi> *list = new LinkedListT<DiaChi> ();
		list = myPa->getLayMangDiaChiBangTenDiaDiemHoacToaDo(
				"/Home/FindLocation.xml");
		int count = list->GetCount();
		if (count == 0) {
			Application *pApp = Application::GetInstance();
			String strMessage = L"";
			pApp->GetAppResource()->GetString(L"IDS_MESSAGE_FINDLOCATION_NORESULT",strMessage);
			MessageBox msg;
			msg.Construct("My Map", strMessage,	MSGBOX_STYLE_OK, 3000);
			int i = 0;
			msg.ShowAndWait(i);
		} else {
				DiaChi p;
				if (count > 1) {
					IList *listArg = new ArrayList();
					for (int i = 0; i < count; i++) {
						list->GetAt(i, p);
						listArg->Add(*(new DiaChi(p)));
					}
					FormManager *pFormManager = null;
					FormManager::GetInstance(pFormManager);
					Form *pFormResult = null;
					result r = pFormManager->GetForm(ShowFindLocationResultForm::GetFormId(), pFormResult);
					if (IsFailed(r)) {
						return;
					}
					pFormResult->SendUserEvent(ShowFindLocationResultForm::REQUEST_SET_RESULT_DATE, listArg);
					pFormManager->SetCurrentForm(ShowFindLocationResultForm::GetFormId());
				} else {
					list->GetAt(0, p);

					WebController::SetMarkerN(p.toaDo.lat, p.toaDo.lng, p.tenDiaDiem, String(L"LocationIcon.png"), true);
				}
			}
			list->RemoveAll();
			delete list;
			return;
		}
		if (currentDownloadTask == REQUEST_READRESULT) {
			MyParserXml *pMyParserXml = new MyParserXml();

			LinkedListT<DiaChi> *pListDiaChi = pMyParserXml->layGiaTriVaoMangPlaceMarkN((char*)path.GetPointer());
			pHuongDanBangGiongNoi = HuongDanDuongDiBangGiongNoi::GetInstance();
			pHuongDanBangGiongNoi->SetMode(HuongDanDuongDiBangGiongNoi::GOOGLE_MODE);
			GoogleReader *googleReader = (GoogleReader*)pHuongDanBangGiongNoi->GetReader();
			googleReader->SetLanguage(GoogleReader::VIETNAMESE);
			pHuongDanBangGiongNoi->read(pListDiaChi);
			pHuongDanBangGiongNoi->Run();
		}
	}

void WebForm::OnDataDownloadComplete(int statusCode, ByteBuffer *data) {
	AppLog("status Code: %d", statusCode);
	if (currentDownloadTask == REQUEST_FINDIRECTION) {
		//complete
		Utf8Encoding encoding;
		if (statusCode == 200) {

			String path = L"";
			result r = encoding.GetString(*data, path);
			if (IsFailed(r)) {
				Application *pApp = Application::GetInstance();
				String error = L"";
				pApp->GetAppResource()->GetString(L"IDS_FINDDRECTION_ERROR_NORESULT", error);
				String appName = L"";
				pApp->GetAppResource()->GetString(L"IDS_APPLICATION_NAME", appName);
				MessageBox message;
				message.Construct(appName, error, MSGBOX_STYLE_OK);
				int i;
				message.ShowAndWait(i);
			} else {
				WebController::SetDirection(path);
				if (m_readResult == true) {
					currentDownloadTask = REQUEST_READRESULT;
					String downloadPath = L"http://maps.google.com/maps?hl=vi";
					downloadPath.Append(L"&saddr=");
					downloadPath.Append(m_startPoint);
					downloadPath.Append(L"&daddr=");
					downloadPath.Append(m_endPoint);
					downloadPath.Append(L"&ie=UTF8&output=kml");
					String utf8DownloadPath = L"";
					r = MyUtil::StringToUTF8String(downloadPath, utf8DownloadPath);
					if (IsFailed(r)) {
						utf8DownloadPath = downloadPath;
					}
					Downloader::downloadAndSave(utf8DownloadPath, L"/Home/read.kml", this);
				}
			}
		} else {
			if (statusCode == 201) {
				Application *pApp = Application::GetInstance();
				String error = L"";
				pApp->GetAppResource()->GetString(L"IDS_FINDDIRECTION_ERROR_NORESULT", error);
				String appName = L"";
				pApp->GetAppResource()->GetString(L"IDS_APPLICATION_NAME", appName);
				MessageBox message;
				message.Construct(appName, error, MSGBOX_STYLE_OK);
				int i;
				message.ShowAndWait(i);
			} else {
				String *text = new String();
				encoding.GetString(*data, *text);
				if (statusCode == 202) {
					IList *list = new ArrayList();
					list->Add(*text);
					list->Add(*(new String(m_endPoint)));
					list->Add(*(new String(m_transport)));
					list->Add(*(new Boolean(m_readResult)));
					list->Add(*(new Boolean(true)));
					FormManager *pFormManager = null;
					FormManager::GetInstance(pFormManager);
					Form *pShowFindDirectionResult = null;
					pFormManager->GetForm(ShowFindDirectionResultForm::GetFormId(), pShowFindDirectionResult);
					pShowFindDirectionResult->SendUserEvent(ShowFindDirectionResultForm::REQUEST_FINDDIRECTION_RESULT, list);
					pFormManager->SetCurrentForm(ShowFindDirectionResultForm::GetFormId());
					return;
				}
				if (statusCode == 203) {
					IList *list = new ArrayList();
					list->Add(*(new String(m_startPoint)));
					list->Add(*text);
					list->Add(*(new String(m_transport)));
					list->Add(*(new Boolean(m_readResult)));
					list->Add(*(new Boolean(false)));
					FormManager *pFormManager = null;
					FormManager::GetInstance(pFormManager);
					Form *pShowFindDirectionResult = null;
					pFormManager->GetForm(ShowFindDirectionResultForm::GetFormId(), pShowFindDirectionResult);
					pShowFindDirectionResult->SendUserEvent(ShowFindDirectionResultForm::REQUEST_FINDDIRECTION_RESULT, list);
					pFormManager->SetCurrentForm(ShowFindDirectionResultForm::GetFormId());
					return;
				}
			}

		}
	}
}

void WebForm::OnDownloadFailed(Osp::Base::String url, Osp::Base::String path) {
	//	AppLog("Download thất bại");
}

void WebForm::FindMultiPoint(IList *pArgs) {
	WebController::RemoveAllMultiPointDirectionListStringItem();
	int count = pArgs->GetCount();
	String *address = null;
	for (int i = 0; i < count; i++) {
		address = (String*) pArgs->GetAt(i);
		WebController::AddListStringItem(*address);
	}
	WebController::DrawMultiPointDirection();

	pArgs->RemoveAll(true);
	delete pArgs;
}

void WebForm::OnUserEventReceivedN(RequestId requestId,
		Osp::Base::Collection::IList* pArgs) {

	switch (requestId) {
	case REQUEST_FINDLOCATION:
		this->TimKiemBanDo(pArgs);

		break;

	case REQUEST_FINDIRECTION:
		this->FindDirection(pArgs);
		break;

	case REQUEST_FINDMULTIPOINT:
		FindMultiPoint(pArgs);
		break;
	default:
		break;
	}
	//delete pArgs;
}

void WebForm::SetCurrentLocation() {
	float longitude;
	float latitude;
	CurrentLocationService::getInstance()->GetCurrentLocation(longitude,
			latitude);
	WebController::SetMyLocationN(latitude, longitude, true);
}

void WebForm::ThongBaoLoi(String value) {
	MessageBox msg;
	msg.Construct("Chào bạn ", value, MSGBOX_STYLE_OK, 3000);
	int i = 0;
	msg.ShowAndWait(i);

}
